// pages/login/login.js
let common_js = require("../../utils/common.js");
let url_js = require("../../utils/url.js");
let user_js = require("../../utils/user.js");
var const_js = require("../../utils/const.js");
var ubt_js = require("../../utils/ubt.js");
var name_js = require("../../utils/ubtButtonName.js");
let api = require("../../utils/apiRequest.js");
let notificationCenter = require('../../thridLib/WxNotificationCenter.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: null,
    submitInfo: {
      phone: '',
      code: '',
      score: 0,
      isPhone: false,
      isLoginEnable: false
    },
    isGetCodeShow: true,
    lastTime: 60,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //业务埋点
    ubt_js.myPageView(common_js.currentPageName(), options);
    //1.禁止转发
    wx.hideShareMenu();
    //2.初始化数据
    this.initData(options);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    // 业务埋点
    ubt_js.myPageViewOut(common_js.currentPageName());
  },

  //初始化数据
  initData: function(options) {
    //userInfo
    let tempUserInfo = user_js.userInfo();
    //submitInfo
    let tmpSubmitInfo = this.data.submitInfo;
    let tmpPhone = options.phone;
    if (tmpPhone) {
      tmpSubmitInfo.phone = tmpPhone;
      tmpSubmitInfo.isPhone = true;
      tmpSubmitInfo.score++;
    }
    this.setData({
      userInfo: tempUserInfo,
      submitInfo: tmpSubmitInfo
    });
  },

  //手机号
  onPhone: function(e) {
    var tmp = e.detail.value;
    var tmpSubmitInfo = this.data.submitInfo;
    if (tmpSubmitInfo.phone.length == 0 && tmp.length > 0) {
      tmpSubmitInfo.score++;
    } else if (tmpSubmitInfo.phone.length > 0 && tmp.length == 0) {
      tmpSubmitInfo.score--;
    }
    tmpSubmitInfo.phone = tmp;
    //isLoginEnable
    if (tmpSubmitInfo.score == 2) {
      tmpSubmitInfo.isLoginEnable = true;
    } else {
      tmpSubmitInfo.isLoginEnable = false;
    }
    this.setData({
      submitInfo: tmpSubmitInfo
    });
  },

  //验证码
  onCode: function(e) {
    var tmp = e.detail.value;
    var tmpSubmitInfo = this.data.submitInfo;
    if (tmpSubmitInfo.code.length == 0 && tmp.length > 0) {
      tmpSubmitInfo.score++;
    } else if (tmpSubmitInfo.code.length > 0 && tmp.length == 0) {
      tmpSubmitInfo.score--;
    }
    tmpSubmitInfo.code = tmp;
    if (tmpSubmitInfo.score == 2) {
      tmpSubmitInfo.isLoginEnable = true;
    } else {
      tmpSubmitInfo.isLoginEnable = false;
    }
    this.setData({
      submitInfo: tmpSubmitInfo
    });
  },

  //点击登录
  onLogin: function(e) {    
    //
    if (!this.data.submitInfo.isLoginEnable) return;
    //phone
    if (!common_js.isPhone(this.data.submitInfo.phone)) {
      common_js.showToast('请输入正确的手机号!');
      return;
    }
    this.requestToLogin(this.data.userInfo.wxUserInfo);
    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.loginLogin);
  },

  //请求登录
  requestToLogin: function(res) {
    let data = {
      code: this.data.userInfo.code,
      loginType: 2,
      mobile: this.data.submitInfo.phone,
      nickname: res.nickName,
      openId: this.data.userInfo.openId,
      profilePhoto: res.avatarUrl,
      sex: res.gender,
      smsCode: this.data.submitInfo.code,
      unionId: ""
    }
    api.wxRequest(url_js.loginLoginUrl, data).then(res => {
      this.handleLoginData(res);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理获取手机验证码
  handleLoginData: function(res) {
    //1.保存当前用户信息
    var tempUserInfo = user_js.userInfo();
    tempUserInfo.userInfo = res.result;
    //保存用户信息
    user_js.saveUserInfo(tempUserInfo);
    //2. post notification
    notificationCenter.postNotificationName(const_js.loginSucessNoti);
    //3.继续购物
    wx.navigateBack({
      delta: 2
    });
  },

  //其他方式-获取微信手机号码
  onGetPhoneNumber: function(e) {
    var denied = e.detail.errMsg.indexOf("fail user deny") != -1;
    if (denied) return;
    //解析获取到的手机号码
    this.requestToDecryptMobile(e.detail);
    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.loginWx);
  },

  //解析手机号码
  requestToDecryptMobile: function(res) {
    let data = {
      code: this.data.userInfo.code,
      encryptedData: res.encryptedData,
      iv: res.iv
    }
    //chain request
    api.wxRequest(url_js.loginDecryptMobileUrl, data).then(res => {
      let loginData = {
        code: this.data.userInfo.code,
        loginType: 1,
        mobile: res.result,
        nickname: this.data.userInfo.wxUserInfo.nickName,
        openId: this.data.userInfo.openId,
        profilePhoto: this.data.userInfo.wxUserInfo.avatarUrl,
        sex: this.data.userInfo.wxUserInfo.gender,
        smsCode: "",
        unionId: ""
      }
      return api.wxRequest(url_js.loginLoginUrl, loginData);
    }).then(res => {
      this.handleLoginData(res);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //协议
  onPolicy: function(e) {

  },

  //获取验证码
  onGetCode: function(e) {
    //手机号
    if (this.data.submitInfo.phone.length == 0) {
      common_js.showToast('手机号码不能为空!');
      return;
    }
    if (!common_js.isPhone(this.data.submitInfo.phone)) {
      common_js.showToast('请输入正确的手机号!');
      return;
    }
    //请求获取手机验证码
    this.requestToGetLoginVerfication(this.data.submitInfo.phone);
  },

  //请求获取手机验证码
  requestToGetLoginVerfication: function(phone) {
    let data = {
      code: this.data.userInfo.code,
      mobile: phone
    }
    api.wxRequest(url_js.loginVerficationUrl, data).then(res => {
      this.handleVerficationResponseData(res);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理获取手机验证码
  handleVerficationResponseData: function(res) {
    if (res.code == 600) {
      //解析base64数据，输入图形验证码
      let imgBase64data = res.result;
      wx.navigateTo({
        url: '../loginImageCode/loginImageCode?imgBase64Data=' + imgBase64data
      });
      return
    }
    //倒计时
    this.countDwonVerify();
  },

  //更新界面60秒后获取验证码
  countDwonVerify: function() {
    var that = this;
    // 将获取验证码按钮隐藏60s，60s后再次显示
    that.setData({
      isGetCodeShow: (!that.data.isGetCodeShow) //false
    })
    var countdown = 60;
    var settime = function(that) {
      if (countdown == 0) {
        that.setData({
          isGetCodeShow: true
        })
        countdown = 60;
        return;
      } else {
        that.setData({
          isGetCodeShow: false,
          lastTime: countdown
        })
        countdown--;
      }
      setTimeout(function() {
        settime(that)
      }, 1000)
    }
    settime(that);
  }
})